import axios from "axios";
import { Notification } from "element-ui";
import { getToken } from "@/utils/auth";

export function downloadUrlMode(url, mode, param, namestatus) {
  // alert(111)
  Notification.info({
    title: "消息",
    message: "开始执行下载任务",
    duration: 2000,
  });
  let headers = {
    Accept:
      namestatus == "1" ? "application/octet-stream; charset=utf-8" : "*/*",
    Authorization: getToken(),
  };
  axios({
    url: url,
    method: mode,
    data: param,
    headers: headers,
    responseType: "blob",
  })
    .then((res) => {
      let fileName = "";
      let fileType = "";
      let contentDisposition = res.headers["content-disposition"];
      if (contentDisposition) {
        // 正则获取filename的值
        let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        let matches = filenameRegex.exec(contentDisposition);
        if (matches != null && matches[1]) {
          fileName = matches[1].replace(/['"]/g, "");
        }
        // 通过 URLEncoder.encode(pFileName, StandardCharsets.UTF_8.name()) 加密编码的, 使用decodeURI(fileName) 解密
        fileName = decodeURI(fileName);
        // 通过 new String(pFileName.getBytes(), StandardCharsets.ISO_8859_1) 加密编码的, 使用decodeURI(escape(fileName)) 解密
        fileType = fileName.substring(fileName.lastIndexOf("."));
      }
      const blob = new Blob([res.data], {
        type: "application/" + fileType,
      });
      let link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      window.setTimeout(function () {
        URL.revokeObjectURL(blob);
        document.body.removeChild(link);
      }, 0);
    })
    .catch((err) => {
      setTimeout(() => {
        Message({
          message: "未找到附件，暂时无法下载！",
          type: "error",
        });
      }, 2000);
    });
}